package com.hs.srm.admin.modules.sys.shiro;

import java.util.Collection;
import java.util.HashMap;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

/**
 * @program: HSSRM
 * @description:
 * @author: Wang Pei Dong
 * @create: 2018-08-09 18:21
 **/
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

	@Override
	protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

		// 判断getRealms()是否返回为空
		assertRealmsConfigured();

		MyUsernamePasswordToken token = (MyUsernamePasswordToken)authenticationToken;
		// 登录类型
		String loginType = token.getLoginType();
		// 所有Realm
		Collection<Realm> realms = getRealms();
		HashMap<String, Realm> realmHashMap = new HashMap<>(realms.size());
		for(Realm realm : realms) {
			if(realm.getName().contains("UserRealm")) {
				realmHashMap.put("default", realm);
			}
			if(realm.getName().contains("ExtRealm")) {
				realmHashMap.put("third", realm);
			}
		}
		if("2".equals(loginType)) {
			return doSingleRealmAuthentication(realmHashMap.get("third"), token);
		}
		return doSingleRealmAuthentication(realmHashMap.get("default"), token);
	}
}
